package com.jinxin.platform.cddjnhjcxtsysset.service.impl;

import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cddjnhjcxtsysset.bean.CdcommondataTableInfo;
import com.jinxin.platform.cddjnhjcxtsysset.bean.CddjnhjcxtsyssetHomeDevice;
import com.jinxin.platform.cddjnhjcxtsysset.bean.CddjnhjcxtsyssetHomeReleva;
import com.jinxin.platform.cddjnhjcxtsysset.bean.param.DeviceParam;
import com.jinxin.platform.cddjnhjcxtsysset.common.Constant;
import com.jinxin.platform.cddjnhjcxtsysset.common.SysUserVO;
import com.jinxin.platform.cddjnhjcxtsysset.mapper.CddjnhjcxtsyssetDeviceMapper;
import com.jinxin.platform.cddjnhjcxtsysset.mapper.CddjnhjcxtsyssetHomeDeviceMapper;
import com.jinxin.platform.cddjnhjcxtsysset.mapper.CddjnhjcxtsyssetHomeRelevaMapper;
import com.jinxin.platform.cddjnhjcxtsysset.rpc.CddjnhjcxtsyssetRpc;
import com.jinxin.platform.cddjnhjcxtsysset.service.ICddjnhjcxtsyssetHomeDeviceService;
import com.jinxin.platform.cddjnhjcxtsysset.utils.IdWorker;
import com.jinxin.platform.cddjnhjcxtsysset.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-10-11
 * @Author: Lingnan
 **/
@Service
public class CddjnhjcxtsyssetHomeDeviceServiceImpl implements ICddjnhjcxtsyssetHomeDeviceService {
    @Autowired
    private CddjnhjcxtsyssetHomeDeviceMapper homeDeviceMapper;
    @Autowired
    private CddjnhjcxtsyssetHomeRelevaMapper homeRelevaMapper;
    @Resource
    private IdWorker idWorker;
    @Autowired
    private CddjnhjcxtsyssetRpc cddjnhjcxtsyssetRpc;
    @Autowired
    private CddjnhjcxtsyssetDeviceMapper cddjnhjcxtsyssetDeviceMapper;

    @Override
    public CddjnhjcxtsyssetHomeDevice selectOne(HashMap param) {
        return homeDeviceMapper.selectOne(param);
    }

    @Override
    public List<CddjnhjcxtsyssetHomeDevice> list(HashMap param) {
        return homeDeviceMapper.list(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveOrUpdate(List<CddjnhjcxtsyssetHomeDevice> records) {
        SysUserVO currentUser = cddjnhjcxtsyssetRpc.getCurrentUser();
        if(currentUser == null){
            return JsonResult.error("获取当前用户信息失败");
        }
        if (records == null || records.size() == 0){
            return JsonResult.error("参数错误，操作失败");
        }
        List<CddjnhjcxtsyssetHomeDevice> list = new ArrayList<>();
        AtomicBoolean isDeleted = new AtomicBoolean(false);
        AtomicBoolean isAdded = new AtomicBoolean(false);
        String newRelevaId = String.valueOf(idWorker.nextId());
        records.forEach(record->{
            String relevaId = record.getRelevaId();
            String type = record.getType();
            if(!StringUtils.isEmpty(relevaId)){
                if(!isDeleted.get()){
                    int count = homeDeviceMapper.deleteByRelevaId(relevaId);
                    //将关联的cdcommondata_table_info表field_29字段全部置为0
                    HashMap param = new HashMap();
                    param.put("relevaId",relevaId);
                    List<CddjnhjcxtsyssetHomeDevice> deviceList = homeDeviceMapper.list(param);
                    Set<String> deviceIdList =
                            deviceList.stream().map(CddjnhjcxtsyssetHomeDevice::getDeviceId).collect(Collectors.toSet());
                    DeviceParam deviceParam = new DeviceParam();
                    deviceParam.setStatus(Constant.STRING_ZERO);
                    deviceParam.setIdList(deviceIdList);
                    int i = cddjnhjcxtsyssetDeviceMapper.batchUpdate(deviceParam);
                    isDeleted.set(true);
                }
                CddjnhjcxtsyssetHomeReleva homeReleva = homeRelevaMapper.selectByKey(relevaId);
                if(homeReleva != null){
                    homeReleva.setWhether(1);
                    homeRelevaMapper.updateByKey(homeReleva);
                }
            }else{
                if(!isAdded.get()){
                    CddjnhjcxtsyssetHomeReleva homeReleva = new CddjnhjcxtsyssetHomeReleva();
                    homeReleva.setId(newRelevaId);
                    homeReleva.setType(type);
                    homeReleva.setWhether(1);
                    homeReleva.setOrgId(currentUser.getOrgId());
                    int count = homeRelevaMapper.insert(homeReleva);
                    if(count > 0){
                        isAdded.set(true);
                    }
                }
                record.setRelevaId(newRelevaId);
            }
            record.setId(Utils.getUuid());
            list.add(record);
            // 如果是总能耗分析开头的则将cdcommondata_table_info表field_29字段置为1
            if(type.startsWith(Constant.PREFIX_SET_TYPE_ZNHFX)){
                CdcommondataTableInfo tableInfo = new CdcommondataTableInfo();
                tableInfo.setId(record.getDeviceId());
                tableInfo.setField29(Constant.STRING_ONE);
                cddjnhjcxtsyssetDeviceMapper.updateByKey(tableInfo);
            }
        });
        if(list.size() == 0){
            return JsonResult.error("参数错误,操作失败");
        }
        int count = homeDeviceMapper.insertBatch(list);
        if(count > 0){
            return JsonResult.ok("保存成功",list.get(0).getRelevaId());
        }else {
            return JsonResult.error("操作失败，请重试");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult delete(String id,String type) {
        if(StringUtils.isEmpty(id)){
            return JsonResult.error("参数错误，删除失败");
        }
        CddjnhjcxtsyssetHomeDevice homeDevice = homeDeviceMapper.selectByKey(id);
        int count = homeDeviceMapper.deleteByKey(id);
        if(count > 0){
            if(homeDevice != null){
                String relevaId = homeDevice.getRelevaId();
                CddjnhjcxtsyssetHomeReleva homeReleva = homeRelevaMapper.selectByKey(relevaId);
                if(homeReleva != null){
                    HashMap param = new HashMap();
                    param.put("relevaId",relevaId);
                    List<CddjnhjcxtsyssetHomeDevice> list = homeDeviceMapper.list(param);
                    if(list.size() == 0){
                        homeReleva.setWhether(2);// 已选择设备全部删除后，将关联状态改为未关联
                        homeRelevaMapper.updateByKey(homeReleva);
                    }
                }
                // 如果是总能耗分析开头的则将cdcommondata_table_info表field_29字段置为0
                if(type.startsWith(Constant.PREFIX_SET_TYPE_ZNHFX)){
                    CdcommondataTableInfo tableInfo = new CdcommondataTableInfo();
                    tableInfo.setId(homeDevice.getDeviceId());
                    tableInfo.setField29(Constant.STRING_ZERO);
                    cddjnhjcxtsyssetDeviceMapper.updateByKey(tableInfo);
                }
            }
            return JsonResult.ok("删除成功","");
        }else {
            return JsonResult.error("删除失败，请重试");
        }
    }
}
